﻿using System.IO;
using System.IO.IsolatedStorage;
using System.Security.Cryptography;
using System.Text;

namespace Appology.SugarSync.Core.Security
{
    public class Crypto
    {
        private static byte[] _iv;
        private static byte[] _key;

        static Crypto()
        {
            EnsureKeysAreGenerated();
        }

        public static void EnsureKeysAreGenerated()
        {
            // check for existence of the Key and IV files...
            using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication())
            {
                var aesManaged = new AesManaged();

                if (!iso.FileExists("IV.bin"))
                {
                    aesManaged.GenerateIV();
                    _iv = aesManaged.IV;

                    using (IsolatedStorageFileStream fs = iso.CreateFile("IV.bin"))
                    {
                        fs.Write(_iv, 0, _iv.Length);
                    }
                }
                else
                {
                    using (IsolatedStorageFileStream fs = iso.OpenFile("IV.bin", FileMode.Open, FileAccess.Read))
                    {
                        var buffer = new byte[fs.Length];
                        fs.Read(buffer, 0, buffer.Length);
                        _iv = buffer;
                    }
                }

                if (!iso.FileExists("Key.bin"))
                {
                    aesManaged.GenerateKey();
                    _key = aesManaged.Key;

                    using (IsolatedStorageFileStream fs = iso.CreateFile("Key.bin"))
                    {
                        fs.Write(_key, 0, _key.Length);
                    }
                }
                else
                {
                    using (IsolatedStorageFileStream fs = iso.OpenFile("Key.bin", FileMode.Open, FileAccess.Read))
                    {
                        var buffer = new byte[fs.Length];
                        fs.Read(buffer, 0, buffer.Length);
                        _key = buffer;
                    }
                }
            }
        }

        public static byte[] Encrypt(string input)
        {
            var aesManaged = new AesManaged();

            ICryptoTransform encryptor = aesManaged.CreateEncryptor(_key, _iv);

            byte[] bytesToEncrypt = Encoding.UTF8.GetBytes(input);

            byte[] encryptedBytes = encryptor.TransformFinalBlock(bytesToEncrypt, 0, bytesToEncrypt.Length);

            return encryptedBytes;
        }

        public static string Decrypt(byte[] input)
        {
            var aesManaged = new AesManaged();

            ICryptoTransform decryptor = aesManaged.CreateDecryptor(_key, _iv);

            byte[] decryptedBytes = decryptor.TransformFinalBlock(input, 0, input.Length);

            return Encoding.UTF8.GetString(decryptedBytes, 0, decryptedBytes.Length);
        }
    }
}